/*
 * Copyright 2013 HVTTGROUP
 * http://hvttgroup.com
 *
 */
package com.hvtt.web.models.datatable;

import java.util.Comparator;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.primefaces.model.SortOrder;

/**
 * Class template Lazy sorter for sort data to dataTable with options :<br/>
 * @author Nguyễn Hoàng Danh
 * @version 1.0
 * 
 * @param sortField is List<DBObject> read from database
 * @param sortOrder is Array fields you want filter
 */
public class DefaultLazyDataSorter<T> implements Comparator<T> {

    private String sortField;
    private SortOrder sortOrder;

    public DefaultLazyDataSorter(String sortField, SortOrder sortOrder) {
        this.sortField = sortField;
        this.sortOrder = sortOrder;
    }

    @Override
    public int compare(T o1, T o2) {
        try {
            Object value1 = FieldUtils.readDeclaredField(o1, this.sortField,true);
            Object value2 = FieldUtils.readDeclaredField(o2, this.sortField,true);
            int value = ((Comparable) value1).compareTo(value2);
            return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}